<?php
@set_time_limit(0);

function chk_folder($filename)
{
	$fp_load = @fopen("$filename", "rb");
	if ( $fp_load )
	{
		return true;
	}
	else
	{
		return false;
	}
}
function getClosestElement($array, $value) 
{
	$size = count($array);
	$tmp = -1;
	if ($size > 0) 
	{
		//echo max($array)."<br><br>";
		//$ret = max($array);
		 while (list($key, $va) = each($array)) 
		 {			 
			 $diff = abs($va - $value);			
			 if($tmp == -1)
			 {
				 $tmp = $diff;
				 $k = $key;
				 //echo "1st ".$key." & ".$diff." = ".$value." diff ".$tmp."<br><br><br>";
				
			 }
			 else
			 {
				 //echo $key." & ".$diff." = ".$value." diff ".$tmp."<br>";
				 if($tmp > $diff) 
				 {
					 $tmp = $diff;
					 $k = $key;
				 }
			}
		}
		//echo "<br> ".$key." ".$va." & ".$diff." = ".$value." diff ".$tmp."<br>";
		return $k;
		//echo "<br><br>";
	}
	else 
	{
	  return NULL;
	}
	
}
if($recordUserInfo[ci_clientType] == "Client" && $recordUserInfo[ui_isAdmin] == "1")
{
	$devices_query =  "SELECT * FROM tb_deviceinfo,tb_client_subscription WHERE tcs_isActive = 1 AND tcs_deviceId = di_id AND di_clientId =".$_SESSION[clientID]." AND di_status = 1 ORDER BY di_deviceName,di_deviceId ASC";
}
else if($recordUserInfo[ci_clientType] == "Client" && $recordUserInfo[ui_isAdmin] == "0" && $recordUserInfo[ui_roleId] == "1")
{
	$devices_query = "SELECT * FROM tb_deviceinfo,tb_client_subscription WHERE tcs_isActive = 1 AND tcs_deviceId = di_id AND di_status = 1 AND di_clientId=".$_SESSION[clientID]." AND di_assignedUserId = ".$_SESSION[userID]." ORDER BY di_deviceName,di_deviceId ASC";
}
//echo $devices_query;
//$devices_query =  "SELECT * FROM tb_deviceinfo WHERE di_clientId =".$_SESSION[clientID]." AND di_status = 1 ORDER BY di_deviceName,di_deviceId ASC";
$devices_resp = mysql_query($devices_query);	
?>

<script type="text/javascript" language="javascript">
jQuery(function() {

    //$("#time3, #time4").timePicker();
	 $("#time3, #time4").timePicker({
	  startTime: "12:01 AM", // Using string. Can take string or Date object.
	  endTime: "11:59 PM", // Using Date object here.
	  show24Hours: false,
	  separator: ':',
	  step: 1});    
        
    // Store time used by duration.
    var oldTime = $.timePicker("#time3").getTime();
    
    // Keep the duration between the two inputs.
    $("#time3").change(function() {
      if ($("#time4").val()) { // Only update when second input has a value.
        // Calculate duration.
        var duration = ($.timePicker("#time4").getTime() - oldTime);
        var time = $.timePicker("#time3").getTime();
        // Calculate and update the time in the second input.
        $.timePicker("#time4").setTime(new Date(new Date(time.getTime() + duration)));
        oldTime = time;
      }
    });
    // Validate.
    $("#time4").change(function() {
      if($.timePicker("#time3").getTime() > $.timePicker(this).getTime()) {
        $(this).addClass("error");
      }
      else {
        $(this).removeClass("error");
      }
    });
    
  });
function showFormDiv()
{
	if(document.getElementById('formDiv').style.display=='none')
	{
		document.getElementById('formDiv').style.display = 'block';
		document.getElementById('shLink').innerHTML = "Hide Form";
	}
	else
	{
		document.getElementById('formDiv').style.display = 'none';
		if(document.getElementById('shLink'))
		document.getElementById('shLink').innerHTML = "Show Form";
	}
}
function showPreloader()
{
	var returnVal = validateMapReport()
	if(returnVal == 1)
	{
		document.getElementById('popup_div').innerHTML = '<div id="loading_txt" >Loading...</div>';
		document.frm_map_filter.submit();
	}
}

function hidePreLoader()
{
	document.getElementById('popup_div').innerHTML = '&nbsp;';
}
function days_between(date1, date2) {

    var ONE_DAY = 1000 * 60 * 60 * 24

    var date1_ms = date1.getTime()
    var date2_ms = date2.getTime()

	var difference_ms = date1_ms - date2_ms
	    
    return Math.round(difference_ms/ONE_DAY)

}

function validateMapReport()
{
	if(document.getElementById('map_device_id').value== 0 )
	{
	alert("Select Device"); 
	document.getElementById('map_device_id').focus();
	return 0;  
	}
	
	if(document.getElementById('from_date').value=='')
	{
	alert("Select Date");
	document.getElementById('from_date').focus();
	return 0;  
	}
	var strTime = document.getElementById('time3').value.split(":"); 
	strTime1 = strTime[1].split(" ");
	strTime = (eval(strTime[0])*60)+eval(strTime1[0]);
	
	var endTime = document.getElementById('time4').value.split(":"); 
	endTime1 = endTime[1].split(" ");
	endTime  = (eval(endTime[0])*60)+eval(endTime1[0]);

	var days_diff = parseInt(endTime) - parseInt(strTime);
	
	if(days_diff > 180)
	{ 
		alert("End time should not be greater than 3 hours from start time.");
		return 0;
	}
	
	return 1;
	
}
function sendCSVData()
{
	document.frmTripData.submit();
}
$(function() {
	$( "#from_date" ).datepicker({
		changeMonth: true,
		changeYear: true,
		maxDate: 0,
		showOn: "button",
		buttonImage: "../user/images/calendar.gif",
		buttonImageOnly: true,
		dateFormat : "dd-mm-yy"
	});
});
</script>
<div id="formDiv">
<form id="frm_map_filter" name="frm_map_filter" method="post" action="" onSubmit="return validateMapReport();">      	 
<table class="gridform_final" style="width:75%">
<tr><th colspan="4">Milegae Graph</th></tr>

  <tr>
    <td width="14%" align="right"><span class="form_text">Select Device</span></td>
    <td width="36%" align="left">
    <select name="map_device_id" id="map_device_id" tabindex="1" style="width:100%" onchange="document.frm_map_filter.txtVehicleName.value = this.options[selectedIndex].text">
        <option value="0">Select Device</option>
        <?php 
		while($devices_fetch = @mysql_fetch_assoc($devices_resp)) 
		{
			$renewDate = date("d-m-Y",strtotime("-1 days ".($devices_fetch[tcs_noOfMonths]) ."months ".$devices_fetch[tcs_renewalDateFrom]));
			//echo $date_offline." <= ".date("d-m-Y",strtotime($renewDate))."<br>";
			if(strtotime(date('d-m-Y')) <= strtotime($renewDate))
			{
			if($devices_fetch[di_deviceName])
				$devName = $devices_fetch[di_deviceName];
			else
				$devName = $devices_fetch[di_deviceId];
        ?>
        <option value="<?php echo $devices_fetch[di_deviceId]."#".$devices_fetch[di_imeiId]; ?>" 
        <?php if($_POST[map_device_id] == $devices_fetch[di_deviceId]."#".$devices_fetch[di_imeiId]) echo "selected"; ?>><?php echo $devName; ?></option>
        <?php } } ?>	
        </select>
        <input type="hidden" name="txtVehicleName" id="txtVehicleName" />
     <input type="hidden" name="curdate" id="curdate" value="<?php echo date('Y-m-d'); ?>" />
    </td>
    <td width="14%" align="right"><span class="form_text">Date&nbsp;</span></td>
    <td width="36%" align="left">
    <input type="text" name="from_date" id="from_date" tabindex="2" readonly="true" size="12"value="<?php if(isset($_POST[from_date])) echo $_POST[from_date]; else echo date("d-m-Y"); ?>" style="width:140px;"/></td>
  </tr>              
  <tr>
    <td align="right"><span class="form_text">Start Time &nbsp;</span></td>
    <td align="left"><div><input type="text" name="time3" id="time3" readonly="readonly" tabindex="3" size="7" value="<?php if($_POST[time3]) echo $_POST[time3]; else echo "12:01 AM";?>" /></div></td>
    
    <td  align="right"><span class="form_text">End Time &nbsp;</span></td>
    <td align="left"><div><input type="text" name="time4" id="time4" readonly="readonly" size="7" tabindex="4" value="<?php if($_POST[time4]) echo $_POST[time4]; else echo "11:59 PM";?>" /></div></td>
  </tr>
  
  <tr>
    <td height="33" colspan="4" style="text-align:center">
    <input type="button" name="map_filter_btn"   value="Filter" class="save_btn" tabindex="5"  onclick="showPreloader();"/>
    <input type="hidden" name="map_filter_btn" value="Filter" />
    <input type="button" name="map_cancel_btn" id="map_cancel_btn" value="Reset" class="save_btn" onClick="location.href='index.php?ch=mileage';" tabindex="6" /> 
    <!--<?php if(isset($_POST[map_filter_btn]) && $_POST[map_filter_btn]!='')  { ?>
    <input type="button" name="map_export_btn" id="map_export_btn" value="Export" class="save_btn" style="font-weight:bold;" onClick="sendCSVData();" /> <?php } ?>-->
    </td>
  </tr>
</table>
</form>
</div>
<div id="popup_div" style=" display:block; border:0px;" >

</div>
<?php
if(isset($_POST[map_filter_btn]) && $_POST[map_filter_btn]!='')
{
	
/*print_r($_POST);

exit;*/

?>
<?php
$altData = array();
$sdate = $_POST[from_date];
$srcData = explode("#",$_POST[map_device_id]);

$strtTime = explode(":",date("H:i",strtotime($_POST[time3])));
$strtTime = (($strtTime[0] * 60) + $strtTime[1]);

$endTime = explode(":",date("H:i",strtotime($_POST[time4])));
$endTime = (($endTime[0] * 60) + $endTime[1]);

$diffTime = round(($endTime - $strtTime)/60);

if($diffTime == 0)
{
	$diffTime = 1;
}
//echo $diffTime." ".$strtTime." ".$nextUp."<br>";

$timeArr= array();
$spdLessData =array();
$spdMidData =array();
$spdHighData =array();
$totalDistance=0;
$tripdata = "Date,Device ID,User ID,Start Point,Start Time,End Point,End Time,Duration,Avg. Speed,Dist. Covered";
$tripdata .= "@";
$cnt=0;
$inc = 5;

$getMileage ="select sum(tmsi_kmpd) as totMileage from tb_deviceinfo,tb_speed_meter_info where tmsi_imei = di_imeiId AND di_imeiId = '".$srcData[1]."' order by tmsi_readDate ASC";
$resMileage = $db->query($getMileage);
$fetMileage = @mysql_fetch_assoc($resMileage);
$devMileage = $fetMileage[totMileage];
//exit;

$fuel_sql ="select * from tb_deviceinfo,tb_fuel where imei = di_imeiId AND di_imeiId = '".$srcData[1]."' order by voltage ASC";
$fuel_rows = $db->query($fuel_sql);
$k=0;

$totalDistance = 0;
$dist = 0;

while($fuel_result = @mysql_fetch_assoc($fuel_rows))
{
	$fuel_params[$fuel_result[tanksize]] = $fuel_result[voltage];
	$fuel_port = $fuel_result[di_Fuelport];
	$k++;
}
 

	$file = DATAPATH.date("d-m-Y", strtotime($sdate))."/".$srcData[1].".txt";   
	
	if(chk_folder($file))
	{
		$file1 = @fopen($file, "r");
		if($file1)
		{
			while(!feof($file1))
			{
				$data= fgets($file1);
			}
			$data = getSortedData($data);
		}
		fclose($file1);
		if(count($data)>0)
		{
			 $data1=explode("#",$data);
			 $j1 = 0;
		 //echo count($data1); 
		  while($j1 < count($data1))
		 {
			//$intervals = count($data1)*0.1;
			$data2=explode("@",$data1[$j1]);
			//echo '<pre>'; print_r($data2);echo '</pre>';
			if(count($data2)>1)
			{
				$data3=explode(",",$data2[1]);
				$vehi=$data3[0];
				$geodate = $data3[8]." ".$data3[9];
				$geoTime = date("h:i:s",strtotime($data3[9]));
				
				$curTime = explode(":",$data3[9]);
				$curTime = (($curTime[0]) * 60);

				if($curTime >= $strtTime && $curTime<=$endTime)
				{
					$pos1=calLat($data3[2]);
					$pos2=calLong($data3[1]);
					if(!in_array($geoTime,$timeArr))
					{
						//echo $strtTime." ".$curTime." ".$endTime." ".$data3[3]."<br>";	
						
						if($cnt==0)
						{
							$pits1 =  $pos1;
							$pits2 =  $pos2;
							$devMileageArr [] = 0;							
						}
						else
						{
							
							$pits3 =  $pos1;
							$pits4 =  $pos2;
							$dist = getDistance($pits1, $pits2, $pits3, $pits4);
							//$devMileage += $dist;
							//echo $cnt." ".$totalDistance." ".$dist."<br>";
							$totalDistance += $dist;
							//echo $cnt." ".$totalDistance." ".$dist."<br>";
							$devMileageArr [] = round($totalDistance);
							$pits1 =  $pits3;
							$pits2 =  $pits4;
							
						}
						
						$speedData [] = $data3[3];
						
						$fule_param = $data3[7]; 									
						$d = preg_split("/[\s,]+/",$fule_param);
						foreach($d as $e)
						{
							if(substr($e,0,3)=='['.$fuel_port.'=')
							{
								  $v = str_replace(array('['.$fuel_port.'=',']'),'',$e); 
							}
						 }
						
						if(strlen($v) > 3 )
						{
							//print_r($fuel_params); 
							$v = $v/1000;
							$vl = getClosestElement($fuel_params,$v);
							$fuelData [] = $vl;
								
						} 
						else
						{
							$v = $v/1000;
							$fuelData [] = 0;
						}
						$spdTime [] = "'".date("h:i:s A",strtotime($data3[9]))."'";
						$cnt++; 
						array_push($timeArr,$geoTime);
					}
				}
				
			 }
			
		 	$j1 = $j1+1;
		}
		
		}
	}
	//print_r($devMileageArr);
	
	//exit;
	if(count($speedData)>0 && count($fuelData)>0 && count($devMileageArr)>0)
	{
		$spdTime = implode(",",$spdTime);
		$speedData = implode(',',$speedData);
		$fuelData = implode(',',$fuelData);
		$devMileageArr = implode(',',$devMileageArr);
?>	  

<script type="text/javascript">
showFormDiv();
hidePreLoader();
</script>
<table class="gridform_final" style="width:100%">      
  <tr>
    <th width="90%">Mileage Graph</th>
    <td class="listofusers" align="right"><a href="#" class="error_strings" id="shLink" onClick="showFormDiv();">Show Form</a></td>
</tr>	

<script type="text/javascript">

 var chart;
 $(document).ready(function() {
	chart = new Highcharts.Chart({
		chart: {
			renderTo: 'container',
			margin: [80, 200, 100, 100],
			zoomType: 'xy'
		},
		title: {
			text: 'Fuel & Speed & Mileage Chart',
			style: {
				margin: '10px 0 0 0' // center it
			}
		},
		subtitle: {
			text: 'Between <?php echo $_POST[time3];?> - <?php echo $_POST[time4];?><br>Click and drag in the plot area to zoom in',
			style: {
				margin: '0 0 0 0' // center it
			}
		},
		xAxis: [{
			categories: [<?php echo $spdTime;?>],
		labels: {
			rotation: -90,
			align: 'right',
			style: {
				 font: 'normal 11px Verdana, sans-serif'
			}
		}
		}],
		yAxis: [{ // Primary yAxis
			labels: {
				formatter: function() {
					return this.value ;
				},
				style: {
					color: '#89A54E'
				}
			},
			title: {
				text: 'Mileage',
				style: {
					color: '#89A54E'
				},
				margin: 50
			},
			opposite: true
			
		}, { // Secondary yAxis
			title: {
				text: 'Speed',
				margin: 70,
				style: {
					color: '#4572A7'
				}
			},
			labels: {
				formatter: function() {
					return this.value +' kmph';
				},
				style: {
					color: '#4572A7'
				}
			}
			
		}, { // Tertiary yAxis
			title: {
				text: 'Fuel',
				margin: 80,
				style: {
					color: '#AA4643'
				}
			},
			labels: {
				formatter: function() {
					return this.value +' Ltr';
				},
				style: {
					color: '#AA4643'
				}
			},
			opposite: true,
			offset: 100
		}],
		tooltip: {
			formatter: function() {
				var unit = {
					'Speed': 'kmph',
					'Mileage': ' km',
					'Fuel': 'Ltr'
				}[this.series.name];
				
				return ''+
					this.x +': '+ this.y +' '+ unit;
			}
		},
		legend: {
			layout: 'vertical',
			style: {
				left: '120px',
				bottom: 'auto',
				right: 'auto',
				top: '90px'
			},
			backgroundColor: '#FFFFFF'
		},
		series: [{
			name: 'Speed',
			color: '#4572A7',
			type: 'column',
			yAxis: 1,
			data: [<?php echo $speedData;?>]		
		
		}, {
			name: 'Fuel',
			type: 'spline',
			color: '#AA4643',
			yAxis: 2,
			data: [<?php echo $fuelData;?>]
		
		}, {
			name: 'Mileage',
			color: '#89A54E',
			type: 'spline',
			data: [<?php echo $devMileageArr;?>]
		}]
	});
	
	
});

</script>
<tr>
	<td colspan="2"><div id="container" style="width:auto; height: 500px; margin: 0 auto"></div></td>
</tr>
<?php
  }
  else
  {
  	echo "<tr><td colspan=2>No Data Found</td></tr>";
  }
}///end of post

?> 
</table>